package com.dandelion.api.controller;

import com.dandelion.api.manager.UserAccountManager;
import com.dandelion.api.request.ThirdCredentials;
import com.dandelion.api.request.ThirdLoginPlatform;
import com.dandelion.common.domain.AccessToken;
import com.dandelion.common.domain.UserProfile;
import com.dandelion.common.http.HttpContext;
import com.rockit.core.pojo.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@RestController
@RequestMapping("/user")
public class UserAccountController extends BaseRestController {
    @Autowired
    private UserAccountManager userAccountManager;

    @RequestMapping("/wxlogin")
    public JsonResult trdlogin(@Valid @ModelAttribute ThirdCredentials credentials, BindingResult bindingResult) {
        assertValid(bindingResult);
        credentials.setPlatform(ThirdLoginPlatform.WEIXIN);
        AccessToken token = userAccountManager.wxlogin(credentials);
        return ok(token);
    }

    @RequestMapping("/logout")
    public JsonResult logout() {
        userAccountManager.logout(HttpContext.current().getUserToken());
        return ok();
    }

    @RequestMapping("/profile")
    public JsonResult getUserProfile() {
        Long userId = HttpContext.current().getRequireUserId();
        UserProfile profile = userAccountManager.getUserProfile(userId);
        return ok(profile);
    }
}
